package com.gather.spring.retry.rhlod;

import com.github.rholder.retry.*;
import com.google.common.base.Predicates;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.io.IOException;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * @author kxd
 * @date 2018/12/4 19:22
 * description:使用rHolder retry进行重试，引入框架使用
 */
@Slf4j
public class RHolderRetryDemo {

    @Test
    public void test() throws ExecutionException, RetryException {
        Callable<Boolean> callable = getBooleanCallable();
        Retryer<Boolean> retry = RetryerBuilder.<Boolean>newBuilder()
                .retryIfResult(Predicates.isNull())
                .retryIfExceptionOfType(IOException.class)
                .retryIfRuntimeException()
                .withStopStrategy(StopStrategies.stopAfterAttempt(3))
                .build();
        retry.call(callable);
    }

    @Test
    public void test01() throws ExecutionException, RetryException {
        Callable<Boolean> callable = getBooleanCallable();
        Retryer<Boolean> retryer = RetryerBuilder.<Boolean>newBuilder()
                .retryIfResult(Predicates.isNull())
                .retryIfExceptionOfType(IOException.class)
                .retryIfRuntimeException()
                .withWaitStrategy(WaitStrategies.fixedWait(3, TimeUnit.SECONDS))
                .withStopStrategy(StopStrategies.stopAfterAttempt(3))
                .build();
        retryer.call(callable);
    }

    private static Callable<Boolean> getBooleanCallable() {
        return new Callable<Boolean>() {
            @Override
            public Boolean call() throws Exception {
                log.info("call...");
                throw new RuntimeException();
            }
        };
    }
}
